home *** CD-ROM | disk | FTP | other *** search
- ===========================================================================
- BBS: The Abacus * HST/DS * Potterville, MI
- Date: 06-06-93 (09:31) Number: 122
- From: BRENDA HOLLOWAY Refer#: 85
- To: JEFFERY FOY Recvd: NO
- Subj: Reverse sorting? Conf: (36) C Language
- ---------------------------------------------------------------------------
- JF> Say you have a text file like this:
-
- JF> first
- JF> second
- JF> third
- JF> ...
- JF> six-hundred-ninety-eight
- JF> six-hundred-ninety-nine
- JF> seven thousand
-
-
- JF> How would you reverse the lines (i.e. in the example, seven thousand
- JF> would become the first line, six-hundred-ninety-nine would become the
- JF> second line ... first would become the last line).
-
- If you have Infinite Stack Space (or a small file), you could do it recursively,
- since to reverse any collection of lines, you save off the first line, reverse
- all the others, then write this line out at the end. It works, but is Not Recomm
- ended! 8) However, it's the easiest, and was one of the programs we had to write
- in my LISP class.
-
- If it's possible to read the entire file into memory, it becomes trivial. Read t
- he file in and write it out in reverse order. We'll assume you can't do THAT eit
- her!
-
- A slower way to do it is to create a temporary file the same size as your input,
- then use fseek to write the lines to it, from the end, backwards. Here's a quic
- k program that does this - it reads the input from stdin, so it uses a second te
- mporary file to buffer the input.
-
- // Reverse the lines from stdin, and write them to stdout.
- // usage: REVERSE <input-file >output-file
- // by Brenda Holloway
-
- #include <stdlib.h>
- #include <stdio.h>
-
- void main()
- {
- char temp1[] = "TEMP1.$$$";
- char temp2[] = "TEMP2.$$$";
- FILE *tchan, *tchan2;
-
- tchan = fopen( temp1, "wb+" );
- if( !tchan ) perror( temp1 );
- else
- {
- tchan2 = fopen( temp2, "wb+" );
- if( !tchan2 ) perror( temp2 );
- else
- {
- char iline[256];
- long count=0;
-
- while( fgets( iline, (sizeof iline), stdin ) )
- {
- count += strlen(iline);
- fputs( iline, tchan );
- fputs( iline, tchan2 );
- }
- fseek( tchan, 0, SEEK_SET );
- while( fgets( iline, (sizeof iline), tchan ) )
- {
- fseek( tchan2, (count-=strlen(iline)), SEEK_SE
- fputs( iline, tchan2 );
- }
- fseek( tchan2, 0, SEEK_SET );
- while( fgets( iline, (sizeof iline), tchan2 ) )
- fputs( iline, stdout );
- fclose( tchan ); fclose( tchan2 );
- unlink( temp1 ); unlink( temp2 );
- }
- }
- }
-
-
- --- Maximus 2.01wb
- * Origin: Two Birds -- One Stone BBS (1:216/37)
- SEEN-BY: 1/211 11/2 4 13/13 101/1 108/89 109/25 110/69 114/5 123/19 124/1
- SEEN-BY: 153/752 154/40 77 157/110 159/100 125 430 575 950 203/23 209/209
- SEEN-BY: 261/1023 280/1 390/1 396/1 5 15 2270/1 2440/5 3603/20
-